package com.m31skytech.dungeonstool.blocks;

import com.m31skytech.dungeonstool.DTTeleporter;
import com.m31skytech.dungeonstool.ItemRegistry;
import com.m31skytech.dungeonstool.blockentitys.TeleportControlBlockEntity;
import com.m31skytech.dungeonstool.blockentitys.TeleportPointBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.pathfinder.Target;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;

import javax.annotation.Nullable;
import java.awt.*;
import java.util.Objects;

public class TeleportControlBlock extends Block implements EntityBlock {

    public TeleportControlBlock() {
        super(BlockBehaviour.Properties.of(Material.STONE)
                .strength(-1f, 3600000.0F)
                .requiresCorrectToolForDrops());
    }

    @Nullable
    @Override
    public BlockEntity newBlockEntity(@NotNull BlockPos pos, @NotNull BlockState state) {
        return new TeleportControlBlockEntity(pos, state);
    }


    @Override
    public @NotNull InteractionResult use(BlockState state, Level world, BlockPos pos, Player player
            , InteractionHand hand, BlockHitResult hit) {
        //点击时获取玩家手中的物品
//        ItemStack heldItem = player.getItemInHand(hand); //此处为获取交互手持item，有bug
        ItemStack heldItem = player.getMainHandItem();

        // 检查玩家是否主手手持 DTWands
        if (heldItem.getItem() == ItemRegistry.DT_WANDS.get()) {
            if (!world.isClientSide) {

                if(alreadyBind(pos,world)){
                    return alreadyBindHandler(pos,world,player);
                }else{
                    return doBindingHandler(pos,world,player);
                }
            }
            return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
        //主手空手时
        }else if (heldItem.isEmpty() && InteractionHand.MAIN_HAND==hand){
            if (!world.isClientSide) {
                if(alreadyBind(pos,world)){
                    return doBindTeleport(pos,world,player);
                }
                return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
            }
        }

        return super.use(state, world, pos, player, hand, hit);
    }

    /**判断当前传送点方块是否已被绑定
     *
     * @param pos
     * @param world
     * @return
     */
    private boolean alreadyBind(BlockPos pos,Level world){
        TeleportControlBlockEntity controlBlockEntity
                    = (TeleportControlBlockEntity) world.getBlockEntity(pos);
        if (null!=controlBlockEntity){
            return controlBlockEntity.isBound();
        }
        return false;
    }

    /**已绑定处理逻辑
     *
     * @param pos
     * @param world
     * @param player
     * @return
     */
    private InteractionResult alreadyBindHandler(BlockPos pos,Level world,Player player){
        TeleportControlBlockEntity pointBlockEntity = (TeleportControlBlockEntity) world
                .getBlockEntity(pos);
        assert pointBlockEntity != null;
        // 已经绑定，可以提示玩家或执行其他逻辑
        player.displayClientMessage(
                Component.literal("该传送控制方块(" + pos.getX() + ", " + pos.getY() + ", " + pos.getZ() + ","
                        +pointBlockEntity.getBindDimension()
                        .location()+")已被绑定,空手右击可进行交互。")
                , true);

        return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
    }

    /**未绑定条件下的绑定逻辑
     *
     * @param pos
     * @param world
     * @param player
     * @return
     */
    private InteractionResult doBindingHandler(BlockPos pos,Level world,Player player){
        player.displayClientMessage(
                Component.literal("传送控制方块(" + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()
                        + ","+world.dimension().location()+")已被选中")
                , true);
        //数据处理:玩家nbt添加副本传送控制方块临时位置存储
        player.getPersistentData().putIntArray("selectedControlBlock", new int[]{pos.getX(), pos.getY(), pos.getZ()});
        // 存储维度信息
        player.getPersistentData().putString("selectedControlBlockDimension", world.dimension().location().toString());

        return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS
    }

    /**绑定状态下的传送处理
     *
     * @param pos
     * @param world
     * @param player
     * @return
     */
    private InteractionResult doBindTeleport(BlockPos pos,Level world,Player player){
        //确保被绑定方块存在.
        TeleportControlBlockEntity pointBlockEntity = (TeleportControlBlockEntity) world
                .getBlockEntity(pos);
        assert pointBlockEntity != null;
        BlockPos targetPos = pointBlockEntity.getBindPos();
        ResourceKey<Level>  dimension= pointBlockEntity.getBindDimension();
        //进行人员传送，将交互的成员，传送至目标方块高度+3的位置
        // 将玩家传送至目标方块高度 + 3 的位置
        if (null!= dimension&& null!= targetPos){
            ServerLevel targetWorld = Objects.requireNonNull(world.getServer()).getLevel(dimension);
            // 将玩家传送至目标维度和坐标
            assert targetWorld != null;
            if (targetWorld.equals(world)){
                player.teleportTo(targetPos.getX() + 0.5D, targetPos.getY() + 1.0D, targetPos.getZ() + 0.5D);//该方法为普通传送，无法跨纬度
            }else{
                player.changeDimension(targetWorld,new DTTeleporter(
                        new BlockPos(targetPos.getX() + 0.5D, targetPos.getY() + 1.0D
                                , targetPos.getZ() + 0.5D)));
            }
    }
        return InteractionResult.SUCCESS; // 处理了事件，返回 SUCCESS

    }
}
